﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Common
{
    public static partial class HtmlTranslate
    {
        /// <summary>
        /// Add a query to an URL.
        /// if the URL has not any query,then append the query key and value to it.
        /// if the URL has some queries, then check it if exists the query key already,replace the value, or append the key and value
        /// if the URL has any fragment, append fragments to the URL end.
        /// </summary>
        public static string SafeSetQueryToURL(string key, string value, string url)
        {
            key = key.GetString().Trim();
            value = value.GetString().Trim();

            Dictionary<string, string> dict = SafeGetDictFromUrl(url);

            if (dict.Keys.Contains(key, StringComparer.CurrentCultureIgnoreCase) == true)
            {
                string k = dict.Keys.Where(o => string.Equals(o, key, StringComparison.CurrentCultureIgnoreCase)).First();
                dict.Remove(k);
            }

            dict[key] = value;
            string query = string.Join("&",
                (
                    from i in dict.Keys
                    select (i + "=" + dict[i])
                 ).ToArray()
                 );
            if (query.HasValue())
            {
                return SafeGetUrlName(url) + "?" + query + SafeGetUrlAnnex(url);
            }
            else return SafeGetUrlName(url) + SafeGetUrlAnnex(url);
        }

        public static Dictionary<string, string> SafeGetDictFromUrl(string url)
        {
            url = url.GetString().Replace("&amp;", "&").Trim();
            Dictionary<string, string> dict = new Dictionary<string, string>();

            if (url.HasValue() == false) return dict;
            if (url.Contains("?") == false) return dict;

            string[] urlSects = url.Split(new char[] { '?' }, StringSplitOptions.None);
            if (urlSects.Length < 2) return dict;

            int si = urlSects[1].LastIndexOf("#");
            if (si >= 0)
            {
                urlSects[1] = urlSects[1].Remove(si);
            }

            foreach (string item in urlSects[1].Replace("&amp;", "&").Trim().Split(new char[] { '&' }, StringSplitOptions.None).OrderBy(o => o.Split('=')[0]))
            {
                string[] eachOne = item.Split(new char[] { '=' }, StringSplitOptions.None);
                if (eachOne.Length < 2) continue;

                if (dict.Keys.Contains(eachOne[0], StringComparer.CurrentCultureIgnoreCase))
                {
                    string k = dict.Keys.Where(o => string.Equals(o, eachOne[0], StringComparison.CurrentCultureIgnoreCase)).First();
                    dict.Remove(k);
                }
                dict[eachOne[0]] = item.Substring(item.IndexOf('=') + 1);
            }

            return dict;
        }

        /// <summary>
        /// 得到 Shop/index.aspx?id=2  中的 Shop/index.aspx 部分。去掉后面的部分。
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SafeGetUrlName(string url)
        {
            string retVal = url.GetString().Replace("&amp;", "&").Trim();

            int index = retVal.IndexOf("?");
            if (index >= 0) retVal = retVal.Substring(0, index);
            index = retVal.IndexOf("#");
            if (index >= 0) retVal = retVal.Substring(0, index);
            return retVal;
        }

        public static string SafeGetFileName(string url)
        {
            string retVal = SafeGetUrlName(url);

            int index = retVal.LastIndexOf("/");
            if (index >= 0) retVal = retVal.Substring(index);
            return retVal;
        }

        /// <summary>
        /// 得到 Shop/index.aspx?id=2  中的 index 部分。
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SafeGetUrlSoloName(string url)
        {
            url = url.GetString().Replace("&amp;", "&").Trim();
            int index = url.LastIndexOf("/") + 1;
            return url.Substring(index, url.LastIndexOf(".") - index);
        }

        /// <summary>
        /// 得到 index.aspx?id=2#1 中的 #1
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SafeGetUrlAnnex(string url)
        {
            url = url.GetString().Replace("&amp;", "&").Trim();
            int index = url.LastIndexOf("#");
            if (index < 0) return string.Empty;
            else return url.Substring(index);
        }

        /// <summary>
        /// Remove a query from url
        /// </summary>
        /// <param name="key"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SafeRemoveQueryFromURL(string key, string url)
        {
            key = key.GetString().Trim();

            Dictionary<string, string> dict = SafeGetDictFromUrl(url);

            if (dict.Keys.Contains(key, StringComparer.CurrentCultureIgnoreCase) == false)
            {
                return FriendRemoveQuery(key, url);
            }
            else
            {
                string query = string.Join("&",
                    (
                        from i in dict.Keys
                        where string.Equals(i, key, StringComparison.CurrentCultureIgnoreCase) == false
                        select (i + "=" + dict[i])
                     ).ToArray()
                     );

                if (query.HasValue())
                {
                    return SafeGetUrlName(url) + "?" + query + SafeGetUrlAnnex(url);
                }
                else return SafeGetUrlName(url) + SafeGetUrlAnnex(url);
            }
        }
        public static string SafeGetQueryFromURL(string key, string url)
        {
            string retVal = string.Empty;
            if (url.HasValue() == false) return string.Empty;
            if (url.Contains("?"))
            {
                string[] urlSects = url.Split('?');
                int si = urlSects[1].LastIndexOf("#");
                if (si >= 0)
                {
                    url = url.Remove(si);
                }

                var res = urlSects[1].Replace("&amp;", "&").Trim().Split(new char[] { '&' }, StringSplitOptions.None)
                    .Where(o => string.Equals(o.Split(new char[] { '=' })[0], key, StringComparison.CurrentCultureIgnoreCase));

                if (res.Count() > 0)
                {
                    string ret = res.First();
                    retVal = ret.Substring(ret.IndexOf('=') + 1);
                    //string[] ret = res.First().Split('=');
                    //if (ret.Length >= 2)
                    //{
                    //    retVal = ret[1];
                    //}
                }
            }

            if (retVal.HasValue() == false)
            {
                retVal = FriendGetQuery(key, url);
            }

            return retVal;
        }

        public static string[] SafeGetKeysFromURL(string url)
        {
            if (url.HasValue() == false) return new string[0];
            if (url.Contains("?") == false) return new string[0];
            url = url.GetString().Replace("&amp;", "&").Trim();

            string[] urlSects = url.Split(new char[] { '?' }, StringSplitOptions.None);
            if (urlSects.Length < 2) return new string[0];

            int si = urlSects[1].LastIndexOf("#");
            if (si >= 0)
            {
                urlSects[1] = urlSects[1].Remove(si);
            }

            return urlSects[1].Trim().Split(new char[] { '&' }, StringSplitOptions.None)
                .Select(o => o.Split('=')[0])
                .OrderBy(o => o)
                .ToArray();
        }


    }
}
